import machine
import time
import sys
#import ir8266
from umqtt.simple import MQTTClient

def on():
    pin = machine.Pin(0, machine.Pin.OUT)
    pin.on()
    time.sleep(0.5)
    pin.off()
    
def off():
    pin = machine.Pin(0, machine.Pin.OUT)
    pin.on()
    time.sleep(0.5)
    pin.off()
    
def sub_cb(topic, msg):
    print((topic, msg))
    if topic == b'action/exit/home/202':
        sys.exit(0)
        
    if topic == b'action/on/home/202/ir/1':
        #on()
#         ir8266.send_raw()
        #ir8266.gree_on()
        print("on: ", time.localtime())
        
    elif topic == b'action/off/home/202/ir/1':
        #off()
        #ir8266.gree_off()
        print("off: ", time.localtime())
    
def init(server):
    c = MQTTClient("umqtt_client4", server, keepalive=0)
    c.set_callback(sub_cb)
    c.connect()

    c.subscribe(b"action/+/home/202/#")
    while True:
#         if True:
#             # Blocking wait for message
            c.wait_msg()
#         else:
            # Non-blocking wait for message
#             c.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
#             time.sleep(1)

    c.disconnect()
    
if __name__ == '__main__':
    init('gzhwedu.cn')

    
    